﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Caifu.Clients;

namespace Caifu
{
	public static class NetValueUtil
	{
		public static DataTable GetNetDaily()
		{
			DataTable table = new DataTable();
			table.Columns.Add("FundCode");
			table.Columns.Add("FundName");

			table.Columns.Add("ReportDate", typeof(DateTime));
			table.Columns.Add("UnitNetValue");
			table.Columns.Add("AccumulatedNetValue");

			table.Columns.Add("PreviousReportDate", typeof(DateTime));
			table.Columns.Add("PreviousUnitNetValue");
			table.Columns.Add("PreviousAccumulatedNetValue");

			table.Columns.Add("GrowthValue", typeof(decimal));
			table.Columns.Add("GrowthRate", typeof(decimal));

			table.Columns.Add("GrowthValue_Show");
			table.Columns.Add("GrowthRate_Show");

			var date = TradeDateUtil.GetNetDailyDate();
			var netValues = NetValueClient.GetNetValues(date);
			var dictNetValues = netValues.ToDictionary(p => p.FundId, p => p);
			var previousDate = TradeDateUtil.GetPreviousTradeDate(date);
			var previousNetValues = NetValueClient.GetNetValues(previousDate);
			var dictPreviousNetValues = previousNetValues.ToDictionary(p => p.FundId, p => p);

			var funds = FundClient.GetFunds(FundType.OpenEnd);

			List<DataRow> rows = new List<DataRow>();

			foreach (var fund in funds)
			{
				DataRow row = table.NewRow();
				rows.Add(row);
				row["FundCode"] = fund.Code;
				row["FundName"] = fund.Name;

				NetValue netValue;
				var exist = dictNetValues.TryGetValue(fund.Id, out netValue);
				if (exist)
				{
					row["ReportDate"] = date;
					row["UnitNetValue"] = netValue.UnitNetValue;
					row["AccumulatedNetValue"] = netValue.AccumulatedNetValue;
				}
				NetValue previousNetValue;
				var previousExist = dictPreviousNetValues.TryGetValue(fund.Id, out previousNetValue);
				if (previousExist)
				{
					row["PreviousReportDate"] = previousDate;
					row["PreviousUnitNetValue"] = previousNetValue.UnitNetValue;
					row["PreviousAccumulatedNetValue"] = previousNetValue.AccumulatedNetValue;
				}

				// 最新交易日与上一交易日的数据都存在
				if (exist && previousExist)
				{
					var unitGrowthValue = netValue.UnitNetValue - previousNetValue.UnitNetValue;
					var accumulatedGrowthValue = netValue.AccumulatedNetValue - previousNetValue.AccumulatedNetValue;
					// 单位净值的涨跌值与累计净值的涨跌值一致
					if (unitGrowthValue == accumulatedGrowthValue)
					{
						row["GrowthValue"] = unitGrowthValue;
						row["GrowthRate"] = unitGrowthValue / previousNetValue.UnitNetValue;
						row["GrowthRate_Show"] = (unitGrowthValue / previousNetValue.UnitNetValue).ToString("P2");
					}
				}
			}

			rows = rows.OrderByDescending(p => p.Field<object>("GrowthRate")).ToList();
			rows.ForEach(p => table.Rows.Add(p));
			return table;
		}
	}
}
